// 秒杀商品信息
let seckillData;
let activeFlage = [0, 0, 0, 0];
// 获取商品信息

(function ($) {
    // 获取秒杀商品
    $.ajax({
        url: serverConfig.serverUrl + "/devs/seckill",
        type: 'get',
        async: false,
        success: function (result) {
            if (result.code == 200) {
                seckillData = result.data;
            } else {
                console.log()
            }
        }
    })

    // 主倒计时
    for (let i = 0; i < seckillData.length; i++) {
        let seckill = seckillData[i];
        activeFlage[i] = seckill.status
    }

    var days = 24 * 60 * 60,
        hours = 60 * 60,
        minutes = 60;

    // Creating the plugin
    $.fn.countdown = function (prop) {

        var options = $.extend({
            callback: function () {
            },
            timestamp: 0
        }, prop);

        var left, d, h, m, s, positions;

        // Initialize the plugin
        init(this, options);

        positions = this.find('.position');

        (function tick() {
            let nowTime = new Date().getTime();
            let seckillNum = -1;

            // 判断切换倒计时
            for (let i = 0; i < seckillData.length; i++) {
                if (new Date(seckillData[i].starTime).getTime() - nowTime > 0) {
                    seckillNum = i;
                    break
                }
            }
            for (let i = 0; i < activeFlage.length; i++) {
                // if (activeFlage[i] == 0)
                    listCount(i)
                // 控制卡片
                controllerCard(i)
            }

            // Time left
            if (seckillNum != -1) {
                document.getElementById("h2_seckill_count").innerText = `即将发送第${seckillNum + 1}轮优惠券`
                left = Math.floor((new Date(seckillData[seckillNum].starTime).getTime() - (new Date())) / 1000);
            } else {
                document.getElementById("h2_seckill_count").innerText = `活动已结束请期待下次`
                left = 0;
            }

            if (left < 0) {
                left = 0;
            }

            // Number of days left
            d = Math.floor(left / days);
            updateDuo(0, 1, d);
            left -= d * days;

            // Number of hours left
            h = Math.floor(left / hours);
            updateDuo(2, 3, h);
            left -= h * hours;

            // Number of minutes left
            m = Math.floor(left / minutes);
            updateDuo(4, 5, m);
            left -= m * minutes;

            // Number of seconds left
            s = left;
            updateDuo(6, 7, s);

            // Calling an optional user supplied callback
            options.callback(d, h, m, s);

            // Scheduling another call of this function in 1s
            setTimeout(tick, 1000);
        })();

        // This function updates two digit positions at once
        function updateDuo(minor, major, value) {
            switchDigit(positions.eq(minor), Math.floor(value / 10) % 10);
            switchDigit(positions.eq(major), value % 10);
        }

        return this;
    };

    function init(elem, options) {
        elem.addClass('countdownHolder');

        // Creating the markup inside the container
        $.each(['Days', 'Hours', 'Minutes', 'Seconds'], function (i) {
            $('<span class="count' + this + '">').html(
                '<span class="position">\
                    <span class="digit static">0</span>\
                </span>\
                <span class="position">\
                    <span class="digit static">0</span>\
                </span>'
            ).appendTo(elem);

            if (this != "Seconds") {
                elem.append('<span class="countDiv countDiv' + i + '"></span>');
            }
        });

    }

    // Creates an animated transition between the two numbers
    function switchDigit(position, number) {

        var digit = position.find('.digit')

        if (digit.is(':animated')) {
            return false;
        }

        if (position.data('digit') == number) {
            // We are already showing this number
            return false;
        }

        position.data('digit', number);

        var replacement = $('<span>', {
            'class': 'digit',
            css: {
                top: '-2.1em',
                opacity: 0
            },
            html: number
        });

        // The .static class is added when the animation
        // completes. This makes it run smoother.

        digit
            .before(replacement)
            .removeClass('static')
            .animate({top: '2.5em', opacity: 0}, 'fast', function () {
                digit.remove();
            })

        replacement
            .delay(100)
            .animate({top: 0, opacity: 1}, 'fast', function () {
                replacement.addClass('static');
            });
    }
})(jQuery);

let nowTime;
let seckillTime;
let seckillEndTime;

// 小倒计时
function listCount(index) {
    nowTime = new Date().getTime();
    let h = Math.floor((new Date(seckillData[index].starTime).getTime() - nowTime) / 1000 / 60 / 60)
    let m = Math.floor((new Date(seckillData[index].starTime).getTime() - nowTime) / 1000 / 60 - h * 60)
    let s = Math.floor((new Date(seckillData[index].starTime).getTime() - nowTime) / 1000 - m * 60 - h * 60 * 60)
    seckillTime = new Date(seckillData[index].starTime).getTime();
    seckillEndTime = new Date(seckillData[index].endTime).getTime();
    let jugeTime = (seckillTime - nowTime);
    let jugeEndTime = (seckillEndTime - nowTime)

    if (jugeTime <= 0 && jugeEndTime > 0) {
        // 活动·进行
        activeFlage[index] = 1;

        document.getElementById(`seckill_${index}`).innerText = "活动进行中";
        $(`#end_span_${index}`).css("display", "");
        document.getElementById(`end_span_${index}`).innerText = "活动进行中";
        document.getElementById(`coupon_result_${index}`).innerHTML = `<img class="coupon_img"  src="../imgs/activity/start.jpg"/>`
        document.getElementById(`awards_result_${index}`).innerHTML = `<img class="coupon_img"  src="../imgs/activity/start.jpg"/>`


    } else if (jugeTime > 0 && jugeEndTime > 0) {
        // 活动·未开始

        activeFlage[index] = 0;

        let str = '0'
        if (h < 10)
            h = str + h
        if (m < 10)
            m = str + m
        if (s < 10)
            s = str + s
        document.getElementById(`seckill_${index}`).innerText = `离活动开始还有: ${h} : ${m} : ${s}`;

        $(`#end_span_${index}`).css("display", "");
        document.getElementById(`end_span_${index}`).innerText = "活动还未开始";

    } else if (jugeEndTime <= 0) {
        activeFlage[index] = 2;
        // 活动·结束
        document.getElementById(`seckill_${index}`).innerText = "活动已结束";
        document.getElementById(`coupon_result_${index}`).innerHTML = `<img class="coupon_img"  src="../imgs/activity/endActive.jpg"/>`
        document.getElementById(`awards_result_${index}`).innerHTML = `<img class="coupon_img"  src="../imgs/activity/endActive.jpg"/>`
    }
}

let userInfo;
$(function () {
    $.ajax({
        headers: {
            "token": localStorage.getItem("token")
        },
        type: 'get',
        url: serverConfig.serverUrl + '/devs/user',
        async: false,
        success: function (result) {
            userInfo = result.data;
        }
    })
    $(".well-item").hover(function () {
        $(this).find(".correct").children().removeClass();
        $(this).find(".opposite").children().removeClass();
        $(this).find(".correct").children().addClass("test");
        $(this).find(".opposite").children().addClass('test2');
    }, function () {
        $(this).find(".correct").children().removeClass();
        $(this).find(".opposite").children().removeClass();
        $(this).find(".correct").children().addClass("test2");
        $(this).find(".opposite").children().addClass('test');
    });

    // 页面刷新同时重新加载小倒计时
    for (let index = 0; index < seckillData.length; index++) {
        listCount(index)
    }
})

function controllerCard(i) {
    // console.log("active")
    let status = activeFlage[i]
    if (status == 0) {
        document.getElementsByClassName("well-item")[i].onclick = function () {
            layer.msg('活动还未开始!', {icon: 2})
        }
    } else if (status == 1) {
        document.getElementsByClassName("well-item")[i].onclick = function () {
            if (userInfo == undefined) {
                layer.msg('请先登录!', {icon: 2})
            } else {
                toBuying(userInfo.id, i)
            }
        }
    } else if (status == 2) {
        // console.log("end")
        document.getElementsByClassName("well-item")[i].onclick = function () {
            layer.msg('活动已结束!', {icon: 2})
        }
        document.getElementById(`seckill_${i}`).innerText = "活动已结束";
        document.getElementById(`coupon_result_${i}`).innerHTML = `<img class="coupon_img"  src="../imgs/activity/endActive.jpg"/>`
        document.getElementById(`awards_result_${i}`).innerHTML = `<img class="coupon_img"  src="../imgs/activity/endActive.jpg"/>`
        $(`#end_span_${i}`).css('display', '');
    }
}

// 抢购
function toBuying(userId, seckillId) {

    // 控制Card事件
    $(".well-item").eq(seckillId).hover(function () {
        $(this).find(".correct").children().removeClass();
        $(this).find(".opposite").children().removeClass();
        $(this).find(".correct").children().addClass("test");
        $(this).find(".opposite").children().addClass('test2');
    }, function () {
        $(this).find(".correct").children().removeClass();
        $(this).find(".opposite").children().removeClass();
        $(this).find(".correct").children().addClass("test");
        $(this).find(".opposite").children().addClass('test2');
    });
    $.ajax({
        url: serverConfig.serverUrl + `/devs/seckill/${userId}/${seckillId + 1}`,
        type: 'get',
        success: function (result) {
            if (result.code == 200) {
                layer.msg('恭喜你,抢购成功，可前往个人中心查看!', {icon: 1})
            } else if (result.code == 502) {
                layer.msg('已经售空!', {icon: 2})
            } else if (result.code == 201) {
                layer.msg('不能重复抢购!', {icon: 2})
            } else if (result.code == 503) {
                layer.msg('活动已结束!', {icon: 2})
            } else if (result.code == 501) {
                layer.msg('活动尚未开始!', {icon: 2})
            }
        }
    })
}

